package de.ars.client.paintSystems;

import com.sun.lwuit.Display;
import com.sun.lwuit.Graphics;

import de.ars.client.screens.MainScreen;

public class LoopPaintSystem
{
    GUIThread gUIThread = null;
    Graphics graphics;
    MainScreen form = null;

    private byte sleep = 2;
    
    private class GUIThread extends Thread
    {
        private boolean b_Cancel = false;

        public void run()
        {
            while( !b_Cancel )
            { 
                form.myPaint( Display.getInstance().getGraphics() );
               
                if (sleep == 0)
                {
                    try
                    {
                        Thread.sleep( 0 );
                    }
                    catch( InterruptedException e )
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                else if (sleep == 1)
                {
                    try
                    {
                        Thread.sleep( 1 );
                    }
                    catch( InterruptedException e )
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                else
                    Thread.yield();
            }
        }

        public void interrupt()
        {
            b_Cancel = true;
            super.interrupt();
        }
    }
    
    public void switchSleepYield()
    {
        this.sleep++;
        if (this.sleep > 2)
            this.sleep = 0;
    }

    public LoopPaintSystem( MainScreen form )
    {
        this.form = form;
        gUIThread = new GUIThread();
    }
    
    public void setGraphics( Graphics graphics )
    {
        this.graphics = graphics;
    }

    public void start()
    {
        if( !gUIThread.isAlive() )
            gUIThread.start();
    }

    public void stop()
    {
        gUIThread.interrupt();
    }
    
    public byte getSleepState()
    {
        return this.sleep;
    }
}
